package cn.starboot.tim.common.util;


import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

/**
 * 汉字转换位汉语拼音，英文字符不变
 */
public class Cn2Spell {

	public static StringBuffer sb = new StringBuffer();

	/**
	 * 获取汉字字符串的首字母，英文字符不变     * 例如：阿飞→af
	 */
	public static String getPinYinHeadChar(String chines) {
		sb.setLength(0);
		char[] chars = chines.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (char aChar : chars) {
			if (aChar > 128) {
				try {
					sb.append(PinyinHelper.toHanyuPinyinStringArray(aChar, defaultFormat)[0].charAt(0));
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				sb.append(aChar);
			}
		}
		return sb.toString();
	}

	/**
	 * 获取汉字字符串的第一个字母
	 */
	public static String getPinYinFirstLetter(String str) {
		sb.setLength(0);
		char c = str.charAt(0);
		String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
		if (pinyinArray != null) {
			sb.append(pinyinArray[0].charAt(0));
		} else {
			sb.append(c);
		}
		return sb.toString();
	}

	/**
	 * 获取汉字字符串的汉语拼音，英文字符不变
	 */
	public static String getPinYin(String chines) {
		sb.setLength(0);
		char[] nameChar = chines.toCharArray();
		HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
		defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		for (char c : nameChar) {
			if (c > 128) {
				try {
					sb.append(PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat)[0]);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}
}

